package com.wisdytech.common.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class WebSocketServerHandlerInitializer  extends ChannelInitializer<Channel> {

    private final String webSocketUri;

    private final ChannelGroup group;

    public WebSocketServerHandlerInitializer(ChannelGroup group,String webSocketUri) {
        this.group = group;
        this.webSocketUri = webSocketUri;
    }

    @Override
    protected void initChannel(Channel channel) throws Exception {
        ChannelPipeline pipeline = channel.pipeline();
        //处理日志
        pipeline.addLast(new LoggingHandler(LogLevel.INFO));

        // TODO 处理心跳
        // HTTP解码器可能会将一个HTTP请求解析成多个消息对象
        // 经过HttpServerCodec解码之后，一个HTTP请求会导致后面的handler channelRead()方法调用多次
        pipeline.addLast(new HttpServerCodec());
        //该通道处理器主要是为了处理大文件传输的情形。大文件传输时，需要复杂的状态管理，而ChunkedWriteHandler实现这个功能。
        // 不需要，目前只返回消息，不返回html文件
        //pipeline.addLast(new ChunkedWriteHandler());
        //可以用HttpObjectAggregator 将多个消息转换为单一的一个FullHttpRequest，如下：
        pipeline.addLast(new HttpObjectAggregator(64 * 1024));
        pipeline.addLast(new HttpRequestHandler(webSocketUri));
        pipeline.addLast(new WebSocketServerProtocolHandler(webSocketUri));
        pipeline.addLast(new WebSocketHandler(group));

    }
}
